<template>
	<view class="wanlshop-container" :style="{'--bg': common.appStyle.home_nav_color}">

		<view v-if="common.modulesData.homeModules.page" class="wanlshop-container__head" :style="{
			height: headHeight + 'px', backgroundColor: headerOpacity == 1 ? 'white' : (headerOpacity > 0 && headerOpacity < 1) ? 'rgba(255, 255, 255, 0.5)' : 'transparent'
			//height: headHeight + 'px', backgroundColor: 'white'
		}">
			<view :style="{ paddingTop: headTop + 'px' }" style="flex: 1">
				<view class="navigater flex align-center justify-between">
					<!-- logo -->
					<!-- <image class="logo" :src="headerOpacity == 1 ? '' : '/static/images/default/logo.png'" mode="widthFix"></image> -->
					<view class="logo" :class="headerOpacity == 1 ? 'active' : ''"
						:style="{background: `url(${$wanlshop.oss(common.appStyle.logo)})`}"></view>

					<!-- 搜索框 -->
					<view class="search flex align-center margin-lr-sm round" style="border: 2rpx solid #aaaaaa20">
						<view class="icon text-df  wanl-gray-dark">
							<text class="wlIcon-sousuo1"></text>
						</view>
						<swiper vertical autoplay circular interval="3000">
							<swiper-item @tap="handleSearch('')">
								<text class="wanl-gray-dark text-cut">搜索商品</text>
							</swiper-item>
							<swiper-item v-for="(item, index) in common.modulesData.searchModules" :key="item.keywords"
								@tap="handleSearch(item.keywords)">
								<text class="wanl-gray-dark text-cut">{{ item.keywords }}</text>
							</swiper-item>
						</swiper>
					</view>
				</view>
			</view>
		</view>

		<view
			:style="{ position: 'fixed', top : headHeight + 'px', left: '0px', zIndex: headerZindex, backgroundColor: '#fbfbfb' }">
			<uv-tabs :current="current" :list="productData" lineColor="#fd8c00" :activeStyle="{
				color: '#fd8c00',
			}" @click="toAnchor"></uv-tabs>
		</view>

		<!-- 主体 -->
		<!-- 首页-顶部轮播图 -->
		<swiper class="bg" :indicator-dots="false" circular :autoplay="true" :interval="5000" :duration="1000">
			<swiper-item v-for="(item,index) in indexBg" :key="index" @click="toActivity(item)">
				<view class="swiper-item">
					<image :src="$wanlshop.oss(item.show_img)" mode="widthFix"></image>
				</view>
			</swiper-item>
		</swiper>

		<!-- 首页-主要内容 -->
		<view class="wanlshop-container__main" style="width: 100%;" :style="{'--top': mainTop + 'rpx'}">
			<!-- 头部菜单 -->
			<index-header @toAnchor="toAnchor" :pageData="common.modulesData.categoryModules"
				:appStyle="common.appStyle" :noticeList="noticeList" :activityList="activityList" />
			<view style="background-color: transparent; position: relative;z-index: 50;opacity: 1;">
				<!-- 热销模块 -->
				<index-popular :pageData="popularData" />
				<!-- 产品列表 -->
				<block v-for="(item, index) in productData" :key="index">
					<view class="box" :id="'title-' + item.id" :style="{backgroundColor: item.backgroundColor}">
						<wanlTitle :pageName="item" :pageId="item.id" @SET_Anchorlist="SET_Anchorlist" />
						<wanlProduct :water="item.isWater" :activity="item.activity" :dataList="item.list"
							v-if="item.id != 118" /> <!-- id:118(公益领养分类)-->
						<indexAdopt :activity="item.activity" :dataList="item.list" v-else />
					</view>
				</block>
			</view>
		</view>

		<!-- 弹窗 -->
		<view class="WANL-MODAL" @touchmove.stop.prevent="moveHandle">
			<!-- 版本更新 -->
			<view class="cu-modal" :class="{ show: update.update }">
				<view class="cu-dialog">
					<view class="hade">
						<image :src="$wanlshop.appstc('/common/update.png')" mode="aspectFit"></image>
						<view class="title">
							<view class="text-white text-bold5">{{ update.data.title }}</view>
							<text class="text-white text-bold5">
								最新版本：{{ update.data.versionName }}
							</text>
						</view>
					</view>

					<view class="info">
						<view class="text-lg text-bold5"><text>更新内容：</text></view>
						<rich-text class="wanl-gray-dark" :nodes="update.data.content" />
						<!-- 开始下载 -->
						<view class="margin-top-xl" v-if="update.download.start">
							<view class="flex margin-bottom-sm">
								<view class="cu-progress round striped active">
									<view class="bg-orange" :style="{ width: update.download.progress + '%' }"></view>
								</view>
								<text class="margin-left-sm">{{ update.download.progress }}%</text>
							</view>
							<view class="wanl-gray-dark text-sm text-center">
								<text>
									下载中，请稍等（{{
			$wanlshop.conver(update.download.totalBytesWritten)
		}}/{{
				$wanlshop.conver(update.download.totalBytesExpectedToWrite)
			}}）
								</text>
							</view>
						</view>
						<!-- 开始安装 -->
						<view class="margin-top-xl text-center" v-else-if="update.download.install">
							安装中...
						</view>
						<!-- 更新提示 -->
						<view class="flex justify-around margin-top-xl" v-else>
							<button class="cu-btn radius-bock bg-gray lg" @tap="ignore">
								忽略升级
							</button>
							<button class="cu-btn radius-bock bg-blue lg" @tap="download">
								立刻升级
							</button>
						</view>
					</view>
				</view>
			</view>
		</view>

		<view class="fixed-box">
			<!-- 客服小组件 -->
			<view @tap="$wanlshop.auth('/pages/user/service')">
				<view class="kefu-img" :style="{ background: `url(${$wanlshop.oss(common.appStyle.im_icon)})` }"
					style="width: 90rpx; height: 90rpx; background-size: cover!important;"></view>
			</view>
			<!-- 回到顶部按钮 -->
			<back-top :style="{opacity: headerOpacity}"></back-top>
		</view>

	</view>
</template>

<script>
	import {
		mapState,
		mapActions
	} from 'vuex';
	import common from '../store/modules/common';
	import wanlTitle from '@/components/wanl-page-category-title/wanl-page-category-title.vue';
	import wanlProduct from '@/components/wanl-product/wanl-product.vue';
	import indexHeader from '@/components/index-header/index-header.vue';
	import indexPopular from '@/components/index-popular/index-popular.vue';
	import indexAdopt from '@/components/index-adopt/index-adopt.vue';

	export default {
		components: {
			indexHeader,
			indexPopular,
			wanlProduct,
			wanlTitle,
			indexAdopt
		},
		data() {
			return {
				current: 0,
				wanlsys: {},
				headerZindex: -1, // 层级
				headerOpacity: 0, // 不透明度
				headHeight: 0,
				windowHeight: 0,
				headTop: 0,
				currentItemId: 'home',
				currentData: {},
				scrollLeft: 0,
				isModal: false,
				contentText: {
					contentdown: '下拉加载更多',
					contentrefresh: '加载中',
					contentnomore: '我是有底线的'
				},
				anchorlist: [], // 坐标组

				// 热销产品数据
				popularData: [],
				// 公告列表
				noticeList: [],
				// 首页-顶部轮播图
				indexBg: [],
				// 首页头部-活动列表
				activityList: [],
				params: {
					search: '',
					sort: 'weigh',
					order: 'asc',
					page: 1,
					filter: {},
					op: {}
				}, // 获取商品列表参数
				requestNum: 0, // 请求数量
				otherRequest: 0, // 除分类外的其他请求 如公告、热销等额外请求
			};
		},
		computed: {
			...mapState(['common', 'user', 'update']),

			mainTop() {
				if (this.wanlsys.platform == 'windows') {
					// pc 小程序
					return -(this.headHeight + 160);
				} else {
					return -(this.headHeight + 100);
				}
			},

			// 分类产品列表
			productData() {
				let category = JSON.parse(JSON.stringify(this.common.modulesData.categoryModules));
				
				// 剔除 "为你推荐" 类目
				category = category.filter(item => item.name != '为你推荐')
				// console.log('分类产品列表111111111111111111', category)

				// 获取对应的商品列表和活动信息
				category.forEach(item => {
					this.params.filter.category_id = item.id;
					// console.log('category',item)
					if (item.id != 118) { // id:118(公益领养分类)
						this.params.type = 'goods';
						this.params.op.category_id = 'in';
						this.$api.get({
							loadingTip: '加载中',
							url: '/wanlshop/product/lists',
							data: this.params,
							success: res => {
								this.requestNum++;
								// console.log('产品列表(/wanlshop/product/lists)', res)
								// 插入活动
								item.activity = res.activity || {
									img_url: "",
									target_url: "",
									column: ""
								};

								// 插入背景色 *****临时*****
								// console.log('item',item);
								if (item.name == '宠物用品') {
									item.backgroundColor = "#C1834A";
								} else if (item.name == '营养健康') {
									item.backgroundColor = "#DCA879";
								} else if (item.name == '洗护美容') {
									item.backgroundColor = "#E7CF9F";
								} else {
									item.backgroundColor = "#FFFFFF";
								}

								res.list.data.reverse();

								// 插入商品列表
								// 根据活动的位置判断要展示多少个商品: horizontal: 4个, vertical: 5个;
								if (res.activity?.column ==
									'vertical') {
									item.isWater = true;
									res.list.data = res.list.data.splice(0, 5)
									// console.log('list vertical',list)
									item.list = res.list.data.reverse();
								} else if (!res.activity || res.activity?.column ==
									'horizontal') {
									item.isWater = false;
									res.list.data = res.list.data.splice(0, 6)
									// console.log('list horizontal',list)
									item.list = res.list.data.reverse();
								}
							},
							loadingTip: '加载中'
						});
					} else {
						// 获取公益领养数据列表和活动信息
						this.$api.get({
							loadingTip: '加载中',
							url: '/wanlshop/pet/list',
							success: res => {
								this.requestNum++;
								// console.log('公益领养', res)
								item.activity = res.activity || {
									img_url: "",
									target_url: "",
									column: ""
								};;

								// 倒序
								res.list.splice(6,res.list.length)
								res.list.reverse();

								// 标签处理 字符串转数组
								res.list.forEach(item => {
									item.show_images = item
										.show_images.split(
											',');
									item.tag = item.tag
										.split(',');
									// console.log('item', item)
								})

								if (res.activity?.column ==
									'vertical') {
									item.isWater = true;
								} else if (!res.activity || res.activity?.column ==
									'horizontal') {
									item.isWater = false;
								}
								item.list = res.list;
							}
						});
					}
				})
				// console.log('new-product', category)
				return category;
			}
		},
		watch: {
			// 请求完成后计算锚点位置
			requestNum(n, o) {
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				// console.log('n', n);
				// console.log('finish', this.productData.length + this.otherRequest)
				// 如果当前已完成请求数量 = 分类请求 + 其他请求数量，就开始计算锚点位置
				if (n == this.productData.length + this.otherRequest) {
					setTimeout(() => {
						this.calcAnchor();
						uni.hideLoading();
					}, 1500)
				}
			}
		},
		onLoad() {
			this.wanlsys = this.$wanlshop.wanlsys();
			this.loadIndexBg();
			this.loadActivity();
			this.loadNotice();
			this.GET_Popular();
		},
		onShow() {
			// #ifdef APP-PLUS
			plus.navigator.setFullscreen(false);
			// #endif
			// 计算页面尺寸
			let sys = this.$wanlshop.wanlsys();
			this.headTop = sys.top;
			// this.headHeight = sys.height + uni.upx2px(60);
			this.headHeight = sys.height;
			this.windowHeight = sys.windowHeight;

			setTimeout(() => {
				uni.setNavigationBarColor({
					frontColor: this.$store.state.common.modulesData.homeModules.page ?
						this.$store.state.common.modulesData.homeModules.page.style
						.navigationBarTextStyle : '',
					backgroundColor: this.$store.state.common.modulesData.homeModules.page ?
						this.$store.state.common.modulesData.homeModules.page.style
						.navigationBarBackgroundColor : ''
				});
			}, 200);
		},
		onReady() {
			// 判断网络类型
			uni.getNetworkType({
				success: res => {
					if (res.networkType == '2g' || res.networkType == '3g' || res.networkType == '4g') {
						this.$wanlshop.msg('当前使用非WIFI环境，请注意流量使用');
					} else if (res.networkType == 'none') {
						this.$wanlshop.msg('没有网络');
					}
				}
			});
		},
		onPullDownRefresh() {
			console.log('刷新')
			this.getServices();
			this.loadIndexBg();
			this.loadActivity();
			this.loadNotice();
			this.GET_Popular();
		},
		methods: {
			...mapActions({
				download: 'update/download', // 立即下载
				ignore: 'update/ignore', // 忽略更新
				getServices: 'common/getServices'
			}),
			// 前往活动页
			toActivity(item) {
				if(!item.type_id) return;
				this.$api.post({
					loadingTip: '加载中',
					url: `/wanlshop/activity/detail`,
					data: {
						type: 'banner',
						type_id: item.type_id
					},
					success: result => {
						console.log('type_id', item.type_id)
						console.log('获取活动', result)
						uni.navigateTo({
							url: `/pages/page/activityPage`,
							success: (res) => {
								res.eventChannel.emit('data', {
									activity: result?.title,
									productList: result?.categories || [],
									headerImage: result?.header_img,
									footerImage: result?.footer_img,
								})
							}
						})
					}
				})
			},
			//计算锚点高度
			calcAnchor() {
				this.productData.forEach(item => {
					let query = null;
					// 支付宝小程序不能加后面的.in(this)，是它自身的限制
					// #ifndef MP-ALIPAY
					query = uni.createSelectorQuery().in(this)
					// #endif
					// #ifdef MP-ALIPAY
					query = uni.createSelectorQuery()
					// #endif
					query.select(`#title-${item.id}`).boundingClientRect(rec => {
						// console.log('title rec', rec)
						this.anchorlist.push({
							id: item.id, // 对应模块id
							top: rec.top - this.wanlsys.height - 44 - 10 // 锚点
						})
					}).exec();
				})
			},
			//跳转锚点
			toAnchor(res) {
				let id = typeof(res) === 'number' ? res : res?.id;
				//if(typeof(res) === 'number') {
				//	this.calcAnchor();
				//}
				setTimeout(() => {
					this.anchorlist.forEach(item => {
						if (item.id == id) {
							uni.pageScrollTo({
								scrollTop: item.top,
								duration: 600
							});
						}
					})
				}, 100)
			},
			// 获取首页背景
			async loadIndexBg() {
				// 统计其他请求数量
				this.otherRequest++;
				this.$api.get({
					loadingTip: '加载中',
					url: '/index/banner',
					success: res => {
						console.log('loadIndexBg', res)
						this.requestNum++;
						const arr = [];
						res.forEach(item => {
							arr.push(item);
						})
						this.indexBg = arr;
					}
				})
			},
			// 获取首页顶部活动
			async loadActivity() {
				// 统计其他请求数量
				this.otherRequest++;
				this.$api.get({
					loadingTip: '加载中',
					url: '/index/activity',
					success: res => {
						// console.log('loadActivity', res)
						this.requestNum++;
						this.activityList = res;
					}
				})
			},
			// 获取公告
			async loadNotice() {
				// 统计其他请求数量
				this.otherRequest++;
				this.$api.post({
					loadingTip: '加载中',
					url: '/wanlshop/article/getList',
					data: {
						category: '公告'
					},
					success: res => {
						this.requestNum++;
						res.data.reverse();
						this.noticeList = res.data;
					}
				})
			},
			// 获取热销产品数据
			async GET_Popular() {
				// 统计其他请求数量
				this.otherRequest++;
				this.$api.post({
					loadingTip: '加载中',
					url: '/wanlshop/product/hotsale',
					success: res => {
						this.requestNum++;
						// console.log('GET_Popular', res)
						let arr = [];
						res.data.forEach(item => {
							// 获取热销产品数据
							if (item.type == "hotsale") {
								arr.push(item);
							}
						})
						this.popularData = arr.reverse();
					}
				})
			},
			// 选择Tag
			handleSelect(id, index) {
				this.currentItemId = id;
				this.scrollLeft = (index - 1) * 50;
			},
			// 弹出层
			handleModal() {
				this.isModal = !this.isModal;
			},
			// 动画
			animationFinish(e) {
				//#ifdef APP-PLUS
				this.changeCurrent(e);
				//#endif
			},
			// 滚动的tag
			changeCurrent(e) {
				this.currentItemId = e.detail.currentItemId;
				this.scrollLeft = (e.detail.current - 1) * 50;
			},
			// 解析Url
			getUrlParam(url) {
				var obj = {};
				var data = url.split('?')[1].split('&');
				for (var i = 0; i < data.length; i++) {
					var res = data[i].split('=');
					obj[res[0]] = res[1];
				}
				return obj;
			},
			// 搜索
			handleSearch(text) {
				this.$wanlshop.to(`/pages/page/search?type=goods&keywords=${text}`, 'fade-in', 100);
			},
			//禁止父元素滑动 1.0.3升级
			moveHandle() {},
			getRangeForNumber(number, ranges) {
				for (let i = 0; i <= ranges.length; i++) {
					const range = ranges[i];
					if (range?.length) {
						if (number >= range[0] && number <= range[1]) {
							return i;
						}
					}
				}
				return 0;
			},
			// 页面滚动
			onPageScroll(e) {
				const arrayTop = [...new Set(this.anchorlist.map(item => item.top))];
				const ranges = [];
				for (let i = 0; i <= arrayTop?.length; i++) {
					if (i == 0) {
						ranges.push([0, arrayTop[i]]);
					} else if (i == (arrayTop?.length - 1)) {
						ranges.push([arrayTop[i], 99999999]);
					} else if (i > 0 && i < (arrayTop?.length - 1)) {
						ranges.push([arrayTop[i], arrayTop[i + 1]]);
					}
				}
				this.current = this.getRangeForNumber(e.scrollTop + 10, ranges);

				// 二级分类展示
				this.headerZindex = e.scrollTop > (arrayTop && arrayTop?.length && arrayTop[0] - 44 - 10) ? 98 : -1;
				//导航栏渐变
				let tmpY = 150;
				e.scrollTop = e.scrollTop > tmpY ? 150 : e.scrollTop; //如果当前高度大于250则250否则当前高度
				this.headerOpacity = e.scrollTop * (1 / tmpY); //$headerOpacity 赋值当前高度x（1÷250）
			}
		},
	};
</script>

<style lang="scss">
	.fixed-box {
		position: fixed;
		right: 50rpx;
		z-index: 999;

		bottom: 130rpx;

		/* #ifdef MP */
		bottom: 50rpx;
		/* #endif */

		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		gap: 20rpx;
	}

	.wanlshop-container {
		background-color: var(--bg);

		&__head {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			z-index: 999;
			background-color: transparent;
			//border-radius: 0 0 16rpx 16rpx;
			overflow: hidden;
			display: flex;
			align-items: center;

			.logo {
				width: 160rpx;
				height: 54rpx;
				flex-shrink: 0;
				background-size: auto 100% !important;
				background-position: 0% center !important;

				&.active {
					background-position: 100% center !important;
				}
			}

			.navigater {
				flex: 1;
				// border: 1px solid red;
				height: 60rpx;
				padding-left: 25rpx;
				// padding-right: 25rpx;

				/* #ifdef MP */
				padding-right: 220rpx;
				// background-color: #ffffff;
				/* #endif */

				.search {
					flex: 1;
					background-color: #fff;
					height: 100%;

					.icon {
						margin: 0 20rpx;
					}

					swiper {
						height: 100%;
						width: 100%;
						margin-right: 10rpx;
						font-size: 26rpx;

						swiper-item {
							display: flex;
							align-items: center;
						}
					}
				}
			}

			.toolbar {
				.scroll {
					flex: 1;
					white-space: nowrap;
					overflow: hidden;
					width: 100%;

					&__item {
						position: relative;
						z-index: 2;
						font-size: 28rpx;
						display: inline-flex;
						height: 58rpx;
						align-items: center;
						margin-right: 40rpx;

						&.action {
							position: relative;
							font-weight: bold;
							font-size: 30rpx;

							&::after {
								content: ' ';
								position: absolute;
								bottom: 0;
								left: 50%;
								transform: translateX(-50%);
								height: 4rpx;
								width: 30rpx;
								border-radius: 6rpx;
								background-color: #fff;
							}
						}
					}
				}

				.category {
					box-shadow: #eee -16rpx 0 16rpx -16rpx;
					height: 58rpx;
					font-size: 28rpx;
					padding-left: 25rpx;
				}
			}
		}

		.bg {
			width: 100%;
			overflow: hidden;
			height: 700rpx;
			position: relative;
			top: 0;
			z-index: 0;

			image {
				width: 100%;
			}

		}

		&__main {
			// position: absolute;
			// top: 25%;
			// z-index: 99;
			background-color: transparent;
			// margin-top: calc(100rpx + 650rpx);
			// margin-top: calc(220rpx + var(--top));
			margin-top: var(--top);
			padding-bottom: 50rpx;

			.box {
				background-color: white;
				margin: 20rpx;
				border-radius: 20rpx;
				display: flow-root;
			}

			/* wanlProduct */
			.wanl-product {
				background-color: #ffffff;
			}

			.wanl-waterfall {
				display: flex;
				flex-direction: row;
				align-items: flex-start;

				.wanl-cloumn {
					display: flex;
					flex: 1;
					flex-direction: column;
					height: auto;
					width: 50%;

					.wanl-image {
						width: 100%;
					}

					.warter {
						// box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.2);
					}
				}

				.content {

					.cart-icon {
						width: 44rpx;
						height: 44rpx;

						image {
							width: 100%;
						}
					}
				}
			}

			.product-activity {
				margin-bottom: 14rpx;
				border-radius: 8rpx;
				overflow: hidden;
				// box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.2);

				image {
					width: 100%;
					display: block;
				}
			}
		}

		.kefu-img {
			background-size: cover !important;
		}

		.WANL-MODAL {
			.cu-modal {
				&.top-modal {
					background: rgba(0, 0, 0, 0.6);
					text-align: inherit;

					.cu-dialog {
						background: #fff;
						border-radius: 0 0 18rpx 18rpx;

						.category {
							display: grid;
							grid-template-columns: 1fr 1fr 1fr 1fr 1fr;
							grid-auto-flow: row dense;
							grid-gap: 16rpx;

							.item {
								display: flex;
								align-items: center;
								justify-content: center;
								padding: 12rpx 0;
								border: 2rpx solid transparent;

								&.action {
									background-color: transparent;
									border-color: #f40;
									color: #f40;
									font-weight: bold;
								}
							}
						}
					}
				}
			}
		}
	}
</style>